package com.inspur.gs.sbssdl.sbssgl.sbtz.sbtz.back.commoncmps;

import com.inspur.edp.bef.api.lcp.IStandardLcp;
import com.inspur.edp.bef.core.LcpUtil;
import com.inspur.edp.bef.engine.entity.AssociationInfo;
import com.inspur.edp.caf.db.dbaccess.IDbParameter;
import com.inspur.edp.cef.entity.changeset.ModifyChangeDetail;
import com.inspur.edp.cef.entity.changeset.ValueObjModifyChangeDetail;
import com.inspur.edp.cef.entity.condition.FilterCondition;
import com.inspur.edp.cef.entity.condition.EntityFilter;
import com.inspur.edp.cef.entity.entity.AssoInfoBase;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.entity.entity.IValuesContainer;
import com.inspur.edp.dxc.common.domain.CommonResult;
import com.inspur.edp.dxc.spi.components.BaseBeforeDBUpdateComponent;
import com.inspur.edp.qdp.bql.api.IBqlExecuter;
import com.inspur.edp.qdp.bql.api.OptionType;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.runtime.config.BqlBeanUtil;
import io.iec.edp.caf.sysmanager.api.data.org.GSPSysOrg;
import io.iec.edp.caf.sysmanager.api.manager.org.SysOrgManager;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class SbssSbtzImport extends BaseBeforeDBUpdateComponent {

    // 设备
    private String sb_cfg = "com.inspur.gs.sbssdl.sbssgl.sbtz.sbtz.back.SbssSbtz";
    //设备代码类别
    private String lbbh_cfg = "com.inspur.gs.sbssdl.database.datadict.datadict.back.DMLB";
    //厂区
    private String cq_cfg = "com.inspur.gs.sbssdl.database.datadict.datadict.back.SbssWorkShop";
    //状态
    private String zt_cfg = "com.inspur.gs.sbssdl.database.datadict.datadict.back.SBZT";
    //类级
    private String lj_cfg = "com.inspur.gs.sbssdl.database.datadict.datadict.back.SBLX";

    private HashMap<String, IStandardLcp> lcpMap = new HashMap<>();

    private HashMap<String, IEntityData> cashMap = new HashMap<>();

    public void importDataSetBefore() {
        List<ModifyChangeDetail> details = super.getDetails();

        lcpMap.put("sb", LcpUtil.getLcp(sb_cfg));
        lcpMap.put("lbbh", LcpUtil.getLcp(lbbh_cfg));
        lcpMap.put("cq", LcpUtil.getLcp(cq_cfg));
        lcpMap.put("zt", LcpUtil.getLcp(zt_cfg));
        lcpMap.put("lj", LcpUtil.getLcp(lj_cfg));

        ValueObjModifyChangeDetail bemodify = new ValueObjModifyChangeDetail();
        bemodify.setItem("valueFrom", "文件导入");
        IStandardLcp sbLcp = lcpMap.get("sb");
        sbLcp.modifyVariable(bemodify);


        details = details.parallelStream()
                .filter(detail -> detail.getPropertyChanges().containsKey("sbbh"))
                .peek(d -> {
                    // 填充关联字段
                    fillRelationField(d);
                    // 查询这个detail 是否有相同设备编号 的detail,有就覆盖各个属性
                    IEntityData nowData = checkSameCode(d);
                    if (nowData != null) {
                        d.setID(nowData.getID());
                    }
                })
                .collect(Collectors.toList());

        CommonResult result = super.getResult();
        result.setChangeDetails(details);
    }

    // 填充关联字段
    private void fillRelationField(ModifyChangeDetail detail) {
        String sbbh = detail.getPropertyChanges().get("sbbh").toString();
        AssoInfoBase info = (AssoInfoBase) detail.getPropertyChanges().get("sblb_id");
        String defaultCode = "0520";
        String importCode = defaultCode;
        if (info == null) {
            info = new AssociationInfo();
            detail.setItem("sblb_id", info);
        }else {
            importCode = info.getValue("sblb_id").toString();
        }

        String lbcode = sbbh.substring(0, 12);
        IEntityData lbbhdata = cashMap.get("sblb_id" + lbcode);

        // 通过设备编号去查询设备类别
        if (lbbhdata == null) {
            List<IEntityData> query = getLbbh(lbcode);
            if (!query.isEmpty()) {
                lbbhdata = query.get(0);
                cashMap.put("sblb_id" + lbcode, lbbhdata);
            }
        }

        // 通过表格导入的设备编号去查询类别
        if (lbbhdata == null) {
            lbbhdata = cashMap.get("sblb_id" + importCode);
            if (lbbhdata == null) {
                List<IEntityData> query = getLbbh(importCode);
                if (!query.isEmpty()) {
                    lbbhdata = query.get(0);
                    cashMap.put("sblb_id" + importCode, lbbhdata);
                }
            }
        }

        // 通过默认的编号去填充类别
        if (lbbhdata == null) {
            lbbhdata = cashMap.get("sblb_id" + defaultCode);
            if (lbbhdata == null) {
                List<IEntityData> query = getLbbh(defaultCode);
                if (!query.isEmpty()) {
                    lbbhdata = query.get(0);
                    cashMap.put("sblb_id" + defaultCode, lbbhdata);
                }
            }
        }

        info.setValue("sblb_id", lbbhdata.getID());
        info.setValue("sblb_id_lbmc", lbbhdata.getValue("lbmc"));
        info.setValue("sblb_id_lbbh", lbbhdata.getValue("lbbh"));


        info = (AssoInfoBase) detail.getPropertyChanges().get("abc");
        if (info != null) {
            String abc_name = (String) info.getValue("abc");
            IEntityData iData = getValue("lj", "lxmc", abc_name);

            if (iData != null) {
                info.setValue("abc", iData.getID());
                info.setValue("abc_lxmc", iData.getValue("lxmc"));
                info.setValue("abc_lxbh", iData.getValue("lxbh"));
            } else {
                detail.getPropertyChanges().remove("abc");
            }
        }

        info = (AssoInfoBase) detail.getPropertyChanges().get("zczt");
        if (info != null) {
            String ztName = (String) info.getValue("zczt");

            IEntityData iData = getValue("zt", "ztmc", ztName);
            if (iData != null) {
                info.setValue("zczt", iData.getID());
                info.setValue("zczt_ztmc", iData.getValue("ztmc"));
                info.setValue("zczt_ztbh", iData.getValue("ztbh"));
            } else {
                detail.getPropertyChanges().remove("zczt");
            }
        }

        info = (AssoInfoBase) detail.getPropertyChanges().get("zt");
        if (info != null) {
            String ztName = (String) info.getValue("zt");

            IEntityData iData = getValue("zt", "ztmc", ztName);
            if (iData != null) {
                info.setValue("zt", iData.getID());
                info.setValue("zt_ztmc", iData.getValue("ztmc"));
                info.setValue("zt_ztbh", iData.getValue("ztbh"));
            } else {
                detail.getPropertyChanges().remove("zt");
            }
        }

        info = (AssoInfoBase) detail.getPropertyChanges().get("shop_id");
        if (info != null) {
            String shop_name = (String) info.getValue("shop_id");

            IEntityData iData = getValue("cq", "ShopName", shop_name);
            if (iData != null) {
                info.setValue("shop_id", iData.getID());
                info.setValue("shop_id_ShopName", iData.getValue("ShopName"));
                info.setValue("shop_id_ShopCode", iData.getValue("ShopCode"));
            } else {
                detail.getPropertyChanges().remove("shop_id");
            }
        }

        info = (AssoInfoBase) detail.getPropertyChanges().get("bmbh_id");
        if (info != null) {
            Object value = info.getValue("bmbh_id");
            if (value != null) {
                String bmbh_name = value.toString();

                SysOrgManager sysOrgManager = SpringBeanUtils.getBean(SysOrgManager.class);
                List<GSPSysOrg> allOrgs = sysOrgManager.getAllOrgs();
                List<GSPSysOrg> data = allOrgs.stream().filter(i -> bmbh_name.contains(i.getName())).collect(Collectors.toList());
                if (!data.isEmpty()) {
                    info.setValue("bmbh_id", data.get(0).getId());
                    info.setValue("bmbh_id_code", data.get(0).getCode());
                    info.setValue("bmbh_id_name", data.get(0).getName());
                } else {
                    detail.getPropertyChanges().remove("bmbh_id");
                }
            }
        }
    }

    private List<IEntityData> getLbbh(String lbbh_code) {
        EntityFilter filter = new EntityFilter();
        ArrayList<FilterCondition> filters = new ArrayList<>(FilterCondition.builder()
                .andEqual("lbbh", lbbh_code)
                .build());
        filter.setFilterConditions(filters);
        return lcpMap.get("lbbh").query(filter);
    }

    // 检查数据库相同编号设备
    private IEntityData checkSameCode(ModifyChangeDetail detail) {
        IStandardLcp sbLcp = lcpMap.get("sb");
        String sbbh = detail.getPropertyChanges().get("sbbh").toString();
        EntityFilter filter = new EntityFilter();
        ArrayList<FilterCondition> filters = new ArrayList<>(FilterCondition.builder()
                .andEqual("sbbh", sbbh)
                .build());
        filter.setFilterConditions(filters);
        List<IEntityData> query = sbLcp.query(filter);
        if (query.isEmpty()) {
            return null;
        }
        return query.get(0);
    }

    private IEntityData getValue(String cfg, String filedName, String value) {
        String cashName = value + filedName;
        if (cashMap.containsKey(cashName)) {
            return cashMap.get(cashName);
        } else {
            IStandardLcp lcp = lcpMap.get(cfg);
            EntityFilter filter = new EntityFilter();
            ArrayList<FilterCondition> filters = new ArrayList<>(FilterCondition.builder()
                    .andEqual(filedName, value)
                    .build());
            filter.setFilterConditions(filters);
            List<IEntityData> query = lcp.query(filter);
            if (!query.isEmpty()) {
                IEntityData iData = query.get(0);
                cashMap.put(cashName, iData);
                return iData;
            }
        }
        return null;
    }

}